package kgame5.kutil {
import flash.display.Sprite;
import flash.display.StageQuality;
import flash.events.Event;
import flash.system.System;
import flash.text.TextField;
import flash.utils.getTimer;

/**
 * @author kangkai
 * 显示帧频和内存的
 * 如果帧频连续一段时间低于指定值，则自动调节
 */
public class FPSMonitor extends Sprite{
	//________________Property__________________
	private var count:int=0;//1秒钟跑了多少真
	private var lastUpdateTime:int=0;
	
	//显示用的
	private var tf:TextField;
	
	private var state:int;//
	private static const 
		STATE_LOW:int=1,//低帧频状态
		STATE_NORMAL:int=0;//常规帧频状态
		
	private var alarmFPS:int;//如果低于这个帧频，将会降低品质
	private var normalFPS:int;//帧频恢复
	
	private var triggerTimes:int;//画面多少次持续低于指定时间.事件被触发了多少次
	private var TriggerTimes:int=3;//画面连续3秒低于，或连续3秒正常，则切换状态
	//_________________Method____________________
	public function FPSMonitor(normalFPS:int,alarmFPS:int){
		T.p("帧频",normalFPS,alarmFPS);
		state=STATE_NORMAL;
		this.normalFPS=normalFPS;
		this.alarmFPS=alarmFPS;
		triggerTimes=0;
		
		tf=new TextField();
		tf.width=70;
		tf.height=20;
		tf.selectable=false;
		tf.textColor=0x00ff00;
		
		addChild(tf);
		
		lastUpdateTime=getTimer();
		count=0;
		
		addEventListener(Event.ENTER_FRAME, efh);
	}
	private function efh(e:Event):void{
		update();
	}
	
	//每帧刷新
	private function update():void{
		//计算fps
		count++;
		var curTime:int=getTimer();
		if(curTime-lastUpdateTime>1000){
			
			//显示字
			tf.text="fps:"+count+" m:"+(int(System.totalMemory/1000)/1000);
			
			//画面状态
			switch(state){
				case STATE_LOW://处于低品质状态
				if(count == this.normalFPS) {
						triggerTimes++;
					if(triggerTimes==this.TriggerTimes){
						T.p("连续几次等于常规帧频，画面品质普通");
						triggerTimes=0;
						state=STATE_NORMAL;
							this.stage.quality=StageQuality.MEDIUM;
						}
				}else{
					triggerTimes=0;
				}
				break;
				case STATE_NORMAL://常规画面品质状态
				if(count<this.alarmFPS){
					triggerTimes++;
					if(triggerTimes==this.TriggerTimes){
						T.p("连续几次低于指定帧频，画面品质变差");
						triggerTimes=0;
						state=STATE_LOW;
						this.stage.quality=StageQuality.LOW;
					}
				}else{
					triggerTimes=0;
				}
				break;
			}
			

			count=0;
			lastUpdateTime=curTime;
		}
	}
}//end of class
}
